$(function() {
	$('body').html($('#template').val().replace(/\{\{(\w+)\}\}/g, function(str, p1) {
		return chrome.i18n.getMessage(p1);
	}));
	var query = chrome.extension.getBackgroundPage().query,
	fields = $('#resultTable').find('.field').html('<img src="loading.gif"/>'),
	logs = $('#logs'),
	gData = null,
	lock = true,
	value = function(props) {
		var obj = gData;
		props = props.split('.');
		for (var i = 0; i < props.length; i++) {
			obj = obj[props[i]];
			if (!obj) {
				return 0;
			}
		}
		return obj;
	},
	join = function(type) {
		if (gData && gData[type]) {
			var array = [];
			for (var key in gData[type]) {
				if (gData[type][key] && gData[type][key].length) {
					array.push(gData[type][key].join('<br>'));
				}
			}
			return array.length ? array.join('<br>') : '';
		} else {
			return '';
		}
	},
	callback = function(data) {
		gData = data;
		fields.each(function() {
			this.innerHTML = value(this.getAttribute('data'));
		});
		var info = join('error');
		if (gData.msg) {
			info = gData.msg;
		} else if (!info) {
			info = chrome.i18n.getMessage('success');
		}
		logs.removeClass('total error redirect').addClass('error').html(info);
		lock = false;
	};
	$('.showLog').click(function() {
		if (gData) {
			var type = this.getAttribute('data'),
			info = join(type);
			logs.removeClass('total error redirect').addClass(type).html(info || '<br>');
		}
	});
	$(document).on('click', '.toggle', function() {
		$('#statusBrief').toggleClass('hidden');
	});
	query({
		cache: true,
		timeout: 20000
	}, callback);
	$('#recheck').click(function() {
		if (lock) {
			return;
		} else {
			lock = true;
		}
		gData = null;
		fields.html('<img src="loading.gif"/>');
		query({ timeout: 20000 }, callback);
	});
});
